Unity横竖滑动列表嵌套(UGUI / ScrollRect) | 您所在的位置:网站首页 › unity3d ngui下拉菜单 › Unity横竖滑动列表嵌套(UGUI / ScrollRect) |
文章目录
一. 前言二. 实现1. 实现原理2. 制作横竖嵌套滑动列表界面3. 运行Unity进行测试4. CustomScrollRect脚本代码
三、答疑
一. 前言
游戏开发过程中,很可能需要制作横竖嵌套的滑动列表。如下效果: 要解决滑动列表嵌套的这个问题,可以根据用户滑动的方向,来进行事件的透传,比如在横向滑动的区域,如果用户是进行竖向滑动,则把事件透传到父级列表,如果父级列表是竖向滑动列表,则可以进行响应,否则继续透传。 UI事件透传接口: ExecuteEvents.Execute(GameObject target, BaseEventData eventData, EventFunction functor) where T : IEventSystemHandler; 2. 制作横竖嵌套滑动列表界面如下,ScrollRect_V为竖向滑动,ScrollRect_H为横向滑动。 运行Unity,即可测试嵌套滑动列表了。 4. CustomScrollRect脚本代码 using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; public class CustomScrollRect :ScrollRect { //父CustomScrollRect对象 private CustomScrollRect m_Parent; public enum Direction { Horizontal, Vertical } //滑动方向 private Direction m_Direction = Direction.Horizontal; //当前操作方向 private Direction m_BeginDragDirection = Direction.Horizontal; protected override void Awake() { base.Awake(); //找到父对象 Transform parent = transform.parent; if(parent){ m_Parent = parent.GetComponentInParent(); } m_Direction = this.horizontal ? Direction.Horizontal : Direction.Vertical; } public override void OnBeginDrag(PointerEventData eventData) { if(m_Parent){ m_BeginDragDirection = Mathf.Abs(eventData.delta.x) > Mathf.Abs(eventData.delta.y) ? Direction.Horizontal : Direction.Vertical; if(m_BeginDragDirection != m_Direction){ //当前操作方向不等于滑动方向,将事件传给父对象 ExecuteEvents.Execute(m_Parent.gameObject, eventData, ExecuteEvents.beginDragHandler); return; } } base.OnBeginDrag(eventData); } public override void OnDrag(PointerEventData eventData) { if (m_Parent) { if (m_BeginDragDirection != m_Direction){ //当前操作方向不等于滑动方向,将事件传给父对象 ExecuteEvents.Execute(m_Parent.gameObject, eventData, ExecuteEvents.dragHandler); return; } } base.OnDrag(eventData); } public override void OnEndDrag(PointerEventData eventData) { if (m_Parent){ if (m_BeginDragDirection != m_Direction){ //当前操作方向不等于滑动方向,将事件传给父对象 ExecuteEvents.Execute(m_Parent.gameObject, eventData, ExecuteEvents.endDragHandler); return; } } base.OnEndDrag(eventData); } public override void OnScroll(PointerEventData data) { if (m_Parent){ if (m_BeginDragDirection != m_Direction){ //当前操作方向不等于滑动方向,将事件传给父对象 ExecuteEvents.Execute(m_Parent.gameObject, data, ExecuteEvents.scrollHandler); return; } } base.OnScroll(data); } } 三、答疑更新(2021-4-7) 有同学私信我说没做出来, 于是今天我重新写了一篇文章,并附上Demo工程,感兴趣的同学可以进行阅读学习。 《Unity UGUI实现横竖嵌套列表ScrollView(利用事件透传),含Demo工程》 |
CopyRight 2018-2019 实验室设备网 版权所有 |